package com.decompiler;

import javax.swing.*;
import javax.swing.Timer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.AbstractMap;

// 导入RSyntaxTextArea相关类
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rsyntaxtextarea.Theme;
import org.fife.ui.rtextarea.RTextScrollPane;

// 导入自定义UI组件
import com.decompiler.ui.RoundedBorder;
import com.decompiler.ui.RoundedPanel;
import com.decompiler.ui.ModernButton;
import com.decompiler.ui.ModernScrollPane;
import com.decompiler.ui.ModernTitleBar;
import com.decompiler.ui.WindowResizer;

/**
 * JAR包反编译工具主类
 * 提供图形界面，支持选择JAR文件、查看反编译代码和导出为标准Java目录结构
 */
public class Main {
    private JFrame frame;
    private JTextField jarPathField;
    private JTextArea logArea;
    private JButton browseButton;
    private JButton decompileButton;
    private JButton exportButton;
    private JTree fileTree;
    private RSyntaxTextArea codeArea; // 使用RSyntaxTextArea替代JTextArea
    private JarDecompiler decompiler;
    private File currentJarFile;
    
    // 图标
    private Icon packageIcon;
    private Icon classIcon;
    private Icon interfaceIcon;
    private Icon enumIcon;
    private Icon jarIcon;
    private Icon xmlIcon;
    private Icon fileIcon; // 通用文件图标
    
    /**
     * 应用程序入口点
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        // 在EDT线程中运行GUI初始化
        SwingUtilities.invokeLater(() -> {
            try {
                // 设置跨平台的Look and Feel
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new Main().initialize();
        });
    }
    
    /**
     * 初始化GUI组件
     */
    private void initialize() {
        // 创建反编译器实例
        decompiler = new JarDecompiler();
        
        // 加载图标
        loadIcons();
        
        // 创建主窗口
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // 自定义关闭行为
        frame.setSize(1200, 800); // 增加窗口大小
        frame.setLocationRelativeTo(null);
        frame.setUndecorated(true); // 移除默认标题栏
        
        // 设置窗口背景色为浅灰色，增加现代感
        frame.getContentPane().setBackground(new Color(245, 245, 245));
        
        // 创建自定义标题栏
        ModernTitleBar titleBar = new ModernTitleBar(frame, "JAR包反编译工具", new Color(59, 89, 152), Color.WHITE, true);
        frame.add(titleBar, BorderLayout.NORTH);
        
        // 添加窗口大小调整功能
        WindowResizer resizer = new WindowResizer(frame);
        
        // 添加窗口关闭事件处理
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                // 关闭反编译器，释放资源
                if (decompiler != null) {
                    decompiler.close();
                }
                // 退出应用程序
                System.exit(0);
            }
        });
        
        // 设置内存管理
        setupMemoryManagement();
        
        // 设置应用程序图标
        if (jarIcon != null && jarIcon instanceof ImageIcon) {
            frame.setIconImage(((ImageIcon)jarIcon).getImage());
        }
        
        // 创建顶部面板，包含JAR文件选择和按钮
        RoundedPanel topPanel = new RoundedPanel(new BorderLayout(5, 0), new Color(255, 255, 255), 15, true);
        topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        RoundedPanel inputPanel = new RoundedPanel(new BorderLayout(10, 0), new Color(250, 250, 250), 10, false);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        JLabel jarLabel = new JLabel("JAR文件路径: ");
        jarLabel.setFont(new Font(jarLabel.getFont().getName(), Font.BOLD, 13));
        
        jarPathField = new JTextField();
        jarPathField.setBorder(new RoundedBorder(new Color(200, 200, 200), 8));
        jarPathField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 13));
        
        browseButton = new ModernButton("浏览...", new Color(70, 130, 180));
        browseButton.setPreferredSize(new Dimension(80, 30));
        
        // 创建一个面板包含文本框和浏览按钮，确保它们垂直对齐
        JPanel textFieldPanel = new JPanel(new BorderLayout(5, 0));
        textFieldPanel.setOpaque(false);
        textFieldPanel.add(jarPathField, BorderLayout.CENTER);
        textFieldPanel.add(browseButton, BorderLayout.EAST);
        
        inputPanel.add(jarLabel, BorderLayout.WEST);
        inputPanel.add(textFieldPanel, BorderLayout.CENTER);
        
        RoundedPanel buttonPanel = new RoundedPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0), new Color(250, 250, 250), 10, false);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5));
        
        decompileButton = new ModernButton("反编译", new Color(46, 125, 50));
        exportButton = new ModernButton("导出", new Color(33, 150, 243));
        exportButton.setEnabled(false);
        
        // 确保按钮大小一致
        Dimension buttonSize = new Dimension(100, 30);
        decompileButton.setPreferredSize(buttonSize);
        exportButton.setPreferredSize(buttonSize);
        
        buttonPanel.add(decompileButton);
        buttonPanel.add(exportButton);
        
        topPanel.add(inputPanel, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.EAST);
        
        // 创建分割面板，左侧是文件树，右侧是代码显示区域
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(250);
        splitPane.setResizeWeight(0.2); // 设置调整权重，使左侧占20%
        splitPane.setContinuousLayout(true); // 拖动时连续布局
        splitPane.setDividerSize(5); // 设置分隔条宽度
        
        // 创建文件树面板
        RoundedPanel treePanel = new RoundedPanel(new BorderLayout(), new Color(255, 255, 255), 15, true);
        treePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建文件树并设置自定义渲染器
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("请先选择JAR文件");
        fileTree = new JTree(root);
        fileTree.setCellRenderer(new JavaElementTreeCellRenderer());
        fileTree.setRowHeight(22); // 增加行高以适应图标
        fileTree.setShowsRootHandles(true);
        fileTree.setRootVisible(true);
        
        // 设置树的外观
        fileTree.putClientProperty("JTree.lineStyle", "Horizontal"); // 水平线条样式
        fileTree.setBackground(new Color(250, 250, 250)); // 设置树的背景色
        
        ModernScrollPane treeScrollPane = new ModernScrollPane(fileTree);
        
        JLabel treeLabel = new JLabel("文件结构:");
        treeLabel.setFont(new Font(treeLabel.getFont().getName(), Font.BOLD, 14));
        
        treePanel.add(treeLabel, BorderLayout.NORTH);
        treePanel.add(treeScrollPane, BorderLayout.CENTER);
        
        // 创建代码显示面板
        RoundedPanel codePanel = new RoundedPanel(new BorderLayout(), new Color(255, 255, 255), 15, true);
        codePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建代码编辑器
        codeArea = new RSyntaxTextArea(20, 60);
        codeArea.setCodeFoldingEnabled(true);
        codeArea.setAntiAliasingEnabled(true);
        codeArea.setEditable(false);
        codeArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); // 默认设置为Java语法高亮
        codeArea.setMarkOccurrences(true); // 标记相同单词
        codeArea.setTabSize(4); // 设置Tab大小
        
        // 应用默认主题
        try {
            Theme theme = Theme.load(getClass().getResourceAsStream(
                    "/org/fife/ui/rsyntaxtextarea/themes/default.xml"));
            theme.apply(codeArea);
            codeArea.setBackground(Color.WHITE); // 设置背景为白色
        } catch (Exception e) {
            // 如果主题加载失败，使用默认设置
            codeArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 13));
            codeArea.setBackground(Color.WHITE);
        }
        
        // 使用RTextScrollPane替代JScrollPane以支持行号显示
        RTextScrollPane codeScrollPane = new RTextScrollPane(codeArea);
        codeScrollPane.setFoldIndicatorEnabled(true);
        
        // 自定义滚动条样式
        codeScrollPane.getVerticalScrollBar().setUI(new ModernScrollPane(null).getVerticalScrollBar().getUI());
        codeScrollPane.getHorizontalScrollBar().setUI(new ModernScrollPane(null).getHorizontalScrollBar().getUI());
        codeScrollPane.setBorder(BorderFactory.createEmptyBorder());
        
        JLabel codeLabel = new JLabel("反编译代码:");
        codeLabel.setFont(new Font(codeLabel.getFont().getName(), Font.BOLD, 14));
        
        codePanel.add(codeLabel, BorderLayout.NORTH);
        codePanel.add(codeScrollPane, BorderLayout.CENTER);
        
        splitPane.setLeftComponent(treePanel);
        splitPane.setRightComponent(codePanel);
        
        // 创建底部日志面板
        RoundedPanel logPanel = new RoundedPanel(new BorderLayout(), new Color(255, 255, 255), 15, true);
        logPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        logPanel.setName("logPanel"); // 设置名称以便于查找
        
        JLabel logLabel = new JLabel("日志:");
        logLabel.setFont(new Font(logLabel.getFont().getName(), Font.BOLD, 13));
        
        logArea = new JTextArea(5, 50);
        logArea.setEditable(false);
        logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        logArea.setBackground(new Color(250, 250, 250));
        
        ModernScrollPane logScrollPane = new ModernScrollPane(logArea);
        
        // 设置日志面板的最小和首选大小，确保在窗口调整时有合适的大小
        logPanel.setMinimumSize(new Dimension(100, 100));
        logPanel.setPreferredSize(new Dimension(frame.getWidth(), 150));
        
        logPanel.add(logLabel, BorderLayout.NORTH);
        logPanel.add(logScrollPane, BorderLayout.CENTER);
        
        // 默认隐藏日志面板
        logPanel.setVisible(false);
        
        // 创建内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBackground(new Color(245, 245, 245));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 创建中央面板，包含分割面板和日志面板
        JPanel centerPanel = new JPanel(new BorderLayout(0, 10));
        centerPanel.setOpaque(false);
        centerPanel.add(splitPane, BorderLayout.CENTER);
        centerPanel.add(logPanel, BorderLayout.SOUTH);
        
        // 添加组件到内容面板
        contentPanel.add(topPanel, BorderLayout.NORTH);
        contentPanel.add(centerPanel, BorderLayout.CENTER);
        
        // 将内容面板添加到主窗口
        frame.add(contentPanel, BorderLayout.CENTER);
        
        // 添加窗口大小变化监听器，调整组件大小
        frame.addComponentListener(new java.awt.event.ComponentAdapter() {
            @Override
            public void componentResized(java.awt.event.ComponentEvent e) {
                // 调整分割面板的分隔位置
                int width = frame.getWidth();
                if (width > 800) {
                    splitPane.setDividerLocation((int)(width * 0.2));
                }
                
                // 如果日志面板可见，调整其高度
                Component logPanel = findComponentByName(frame, "logPanel");
                if (logPanel != null && logPanel.isVisible()) {
                    int height = frame.getHeight();
                    logPanel.setPreferredSize(new Dimension(width, Math.min(150, height / 5)));
                    contentPanel.revalidate();
                }
            }
        });
        
        // 添加事件监听器
        setupEventListeners();
        
        // 显示窗口
        frame.setVisible(true);
        log("应用程序已启动，请选择JAR文件进行反编译。");
    }
    
    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 浏览按钮事件
        browseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                    @Override
                    public boolean accept(File f) {
                        return f.isDirectory() || f.getName().toLowerCase().endsWith(".jar");
                    }
                    
                    @Override
                    public String getDescription() {
                        return "JAR文件 (*.jar)";
                    }
                });
                
                int result = fileChooser.showOpenDialog(frame);
                if (result == JFileChooser.APPROVE_OPTION) {
                    currentJarFile = fileChooser.getSelectedFile();
                    jarPathField.setText(currentJarFile.getAbsolutePath());
                    log("已选择JAR文件: " + currentJarFile.getAbsolutePath());
                }
            }
        });
        
        // 反编译按钮事件 - 优化版本
        decompileButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String jarPath = jarPathField.getText().trim();
                if (jarPath.isEmpty()) {
                    log("错误：请先选择JAR文件");
                    return;
                }
                
                // 禁用按钮，防止重复操作
                decompileButton.setEnabled(false);
                exportButton.setEnabled(false);
                
                // 创建进度对话框
                JDialog progressDialog = new JDialog(frame, "反编译进度", false); // 非模态对话框
                JProgressBar progressBar = new JProgressBar();
                progressBar.setIndeterminate(true); // 使用不确定进度
                JLabel statusLabel = new JLabel("正在准备反编译...");
                JButton cancelButton = new JButton("取消");
                
                // 设置进度对话框布局
                JPanel progressPanel = new JPanel(new BorderLayout(10, 10));
                progressPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
                progressPanel.add(statusLabel, BorderLayout.NORTH);
                progressPanel.add(progressBar, BorderLayout.CENTER);
                progressPanel.add(cancelButton, BorderLayout.SOUTH);
                
                progressDialog.setContentPane(progressPanel);
                progressDialog.setSize(350, 150);
                progressDialog.setLocationRelativeTo(frame);
                progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                
                // 创建反编译任务
                final AtomicBoolean cancelled = new AtomicBoolean(false);
                
                // 取消按钮事件
                cancelButton.addActionListener(event -> {
                    cancelled.set(true);
                    statusLabel.setText("正在取消操作...");
                    cancelButton.setEnabled(false);
                });
                
                // 使用CompletableFuture进行异步处理，提高响应性
                CompletableFuture.supplyAsync(() -> {
                    try {
                        log("开始反编译JAR文件...");
                        File jarFile = new File(jarPath);
                        if (!jarFile.exists() || !jarFile.isFile()) {
                            return new AbstractMap.SimpleEntry<>(false, "错误：JAR文件不存在或不是有效的文件。");
                        }
                        
                        // 更新状态
                        SwingUtilities.invokeLater(() -> statusLabel.setText("正在反编译JAR文件..."));
                        
                        // 执行反编译
                        long startTime = System.currentTimeMillis();
                        boolean success = decompiler.decompileJar(jarFile);
                        long endTime = System.currentTimeMillis();
                        
                        // 检查是否被取消
                        if (cancelled.get()) {
                            return new AbstractMap.SimpleEntry<>(false, "反编译操作已取消");
                        }
                        
                        // 计算反编译时间
                        double seconds = (endTime - startTime) / 1000.0;
                        
                        if (success) {
                            int classCount = decompiler.getDecompiledClasses().size();
                            int nonJavaCount = decompiler.getNonJavaFilesCount();
                            String message = String.format(
                                "反编译完成！已反编译 %d 个类文件，发现 %d 个资源文件，总耗时 %.2f 秒", 
                                classCount, nonJavaCount, seconds);
                            return new AbstractMap.SimpleEntry<>(true, message);
                        } else {
                            return new AbstractMap.SimpleEntry<>(false, "反编译失败，请检查日志获取详细信息。");
                        }
                    } catch (OutOfMemoryError oom) {
                        // 特殊处理内存不足错误
                        System.gc(); // 请求垃圾回收
                        return new AbstractMap.SimpleEntry<>(false, 
                            "内存不足，无法完成反编译: " + oom.getMessage() + 
                            "\n请尝试增加JVM内存或反编译较小的JAR文件。");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        return new AbstractMap.SimpleEntry<>(false, "反编译过程中发生错误: " + ex.getMessage());
                    }
                // 使用自定义线程池，避免使用默认ForkJoinPool
                }, ForkJoinPool.commonPool())
                .thenAcceptAsync(result -> {
                    // 处理结果
                    boolean success = result.getKey();
                    String message = result.getValue();
                    
                    // 记录日志
                    log(message);
                    
                    // 更新UI
                    progressDialog.dispose();
                    
                    if (success) {
                        // 更新文件树
                        updateFileTree(decompiler.getDecompiledClasses());
                        log("请在左侧文件树中选择要查看的类文件。");
                    }
                    
                    // 恢复按钮状态
                    decompileButton.setEnabled(true);
                    exportButton.setEnabled(success);
                }, SwingUtilities::invokeLater); // 确保UI更新在EDT线程中执行
                
                // 显示进度对话框（非模态，不阻塞UI线程）
                progressDialog.setVisible(true);
            }
        });
        
        // 导出按钮事件 - 优化版本
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (decompiler.getDecompiledClasses().isEmpty()) {
                    log("错误：请先反编译JAR文件");
                    return;
                }
                
                // 选择导出目录
                JFileChooser chooser = new JFileChooser();
                chooser.setDialogTitle("选择导出目录");
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                
                if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    File exportDir = chooser.getSelectedFile();
                    
                    // 禁用按钮，防止重复操作
                    decompileButton.setEnabled(false);
                    exportButton.setEnabled(false);
                    
                    // 创建进度对话框
                    JDialog progressDialog = new JDialog(frame, "导出进度", false); // 非模态对话框
                    JProgressBar progressBar = new JProgressBar();
                    progressBar.setIndeterminate(true); // 使用不确定进度
                    JLabel statusLabel = new JLabel("正在准备导出...");
                    JButton cancelButton = new JButton("取消");
                    
                    // 设置进度对话框布局
                    JPanel progressPanel = new JPanel(new BorderLayout(10, 10));
                    progressPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
                    progressPanel.add(statusLabel, BorderLayout.NORTH);
                    progressPanel.add(progressBar, BorderLayout.CENTER);
                    progressPanel.add(cancelButton, BorderLayout.SOUTH);
                    
                    progressDialog.setContentPane(progressPanel);
                    progressDialog.setSize(350, 150);
                    progressDialog.setLocationRelativeTo(frame);
                    progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                    
                    // 创建导出任务
                    final AtomicBoolean cancelled = new AtomicBoolean(false);
                    
                    // 取消按钮事件
                    cancelButton.addActionListener(event -> {
                        cancelled.set(true);
                        statusLabel.setText("正在取消操作...");
                        cancelButton.setEnabled(false);
                    });
                    
                    // 使用CompletableFuture进行异步处理，提高响应性
                    CompletableFuture.supplyAsync(() -> {
                        try {
                            log("开始导出反编译代码到: " + exportDir.getAbsolutePath());
                            
                            // 更新状态
                            SwingUtilities.invokeLater(() -> statusLabel.setText("正在导出反编译代码..."));
                            
                            // 执行导出
                            long startTime = System.currentTimeMillis();
                            boolean success = decompiler.exportDecompiledCode(exportDir);
                            long endTime = System.currentTimeMillis();
                            
                            // 检查是否被取消
                            if (cancelled.get()) {
                                return new AbstractMap.SimpleEntry<>(false, "导出操作已取消");
                            }
                            
                            // 计算导出时间
                            double seconds = (endTime - startTime) / 1000.0;
                            
                            if (success) {
                                // 显示导出统计信息
                                int classCount = decompiler.getDecompiledClasses().size();
                                int nonJavaCount = decompiler.getNonJavaFilesCount();
                                String message = String.format(
                                    "导出成功！已导出 %d 个类文件，已导出 %d 个资源文件，总耗时 %.2f 秒。文件已保存到: %s", 
                                    classCount, nonJavaCount, seconds, exportDir.getAbsolutePath());
                                return new AbstractMap.SimpleEntry<>(true, message);
                            } else {
                                return new AbstractMap.SimpleEntry<>(false, "导出失败，请检查日志获取详细信息。");
                            }
                        } catch (OutOfMemoryError oom) {
                            // 特殊处理内存不足错误
                            System.gc(); // 请求垃圾回收
                            return new AbstractMap.SimpleEntry<>(false, 
                                "内存不足，无法完成导出: " + oom.getMessage() + 
                                "\n请尝试增加JVM内存或导出较小的项目。");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            return new AbstractMap.SimpleEntry<>(false, "导出过程中发生错误: " + ex.getMessage());
                        }
                    // 使用自定义线程池，避免使用默认ForkJoinPool
                    }, ForkJoinPool.commonPool())
                    .thenAcceptAsync(result -> {
                        // 处理结果
                        boolean success = result.getKey();
                        String message = result.getValue();
                        
                        // 记录日志
                        log(message);
                        
                        // 更新UI
                        progressDialog.dispose();
                        
                        // 恢复按钮状态
                        decompileButton.setEnabled(true);
                        exportButton.setEnabled(true);
                    }, SwingUtilities::invokeLater); // 确保UI更新在EDT线程中执行
                    
                    // 显示进度对话框（非模态，不阻塞UI线程）
                    progressDialog.setVisible(true);
                }
            }
        });
        
        // 文件树选择事件
        fileTree.addTreeSelectionListener(e -> {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) fileTree.getLastSelectedPathComponent();
            if (selectedNode == null || selectedNode.isRoot()) {
                return;
            }
            
            // 获取JavaElementInfo对象
            Object userObject = selectedNode.getUserObject();
            if (userObject instanceof JavaElementInfo) {
                JavaElementInfo elementInfo = (JavaElementInfo) userObject;
                String fullName = elementInfo.getFullName();
                String type = elementInfo.getType();
                
                // 如果是包或JAR，不显示内容
                if ("PACKAGE".equals(type) || "JAR".equals(type)) {
                    return;
                }
                
                // 更新窗口标题
                frame.setTitle("JAR包反编译工具 - " + fullName);
                
                // 根据文件类型显示不同内容
                if ("XML".equals(type) || "POM".equals(type) || 
                    "PROPERTIES".equals(type) || "MANIFEST".equals(type) || 
                    "OTHER_FILE".equals(type)) {
                    // 显示非Java文件内容
                    String content = decompiler.getNonJavaFileContent(fullName);
                    if (content != null) {
                        // 设置语法高亮
                        if ("XML".equals(type) || "POM".equals(type)) {
                            codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML);
                        } else if ("PROPERTIES".equals(type)) {
                            codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_PROPERTIES_FILE);
                        } else if (fullName.endsWith(".json")) {
                            codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON);
                        } else if (fullName.endsWith(".yml") || fullName.endsWith(".yaml")) {
                            codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_YAML);
                        } else {
                            codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
                        }
                        
                        // 设置内容
                        codeArea.setText(content);
                        codeArea.setCaretPosition(0);
                        
                        log("显示文件: " + fullName);
                    } else {
                        codeArea.setText("无法获取该文件的内容。");
                        log("无法获取文件内容: " + fullName);
                    }
                } else {
                    // 显示Java类文件的反编译代码
                    String code = decompiler.getDecompiledCode(fullName);
                    if (code != null) {
                        // 设置Java语法高亮
                        codeArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
                        
                        // 设置代码并高亮显示
                        codeArea.setText(code);
                        codeArea.setCaretPosition(0);
                        
                        log("显示类: " + fullName);
                    } else {
                        codeArea.setText("无法获取该类的反编译代码。");
                        log("无法获取类的反编译代码: " + fullName);
                    }
                }
            }
        });
    }
    
    /**
     * 加载图标资源
     */
    private void loadIcons() {
        try {
            // 尝试从资源加载SVG图标
            URL packageUrl = getClass().getResource("/icons/package.svg");
            URL classUrl = getClass().getResource("/icons/class.svg");
            URL interfaceUrl = getClass().getResource("/icons/interface.svg");
            URL enumUrl = getClass().getResource("/icons/enum.svg");
            URL jarUrl = getClass().getResource("/icons/jar.svg");
            URL xmlUrl = getClass().getResource("/icons/xml.svg");
            URL fileUrl = getClass().getResource("/icons/file.svg");
            
            // 创建图标，如果URL不为null
            if (packageUrl != null) packageIcon = new ImageIcon(packageUrl);
            if (classUrl != null) classIcon = new ImageIcon(classUrl);
            if (interfaceUrl != null) interfaceIcon = new ImageIcon(interfaceUrl);
            if (enumUrl != null) enumIcon = new ImageIcon(enumUrl);
            if (jarUrl != null) jarIcon = new ImageIcon(jarUrl);
            if (xmlUrl != null) xmlIcon = new ImageIcon(xmlUrl);
            if (fileUrl != null) fileIcon = new ImageIcon(fileUrl);
            
            // 检查图标是否成功加载，如果没有则使用默认图标
            if (packageIcon == null) {
                packageIcon = UIManager.getIcon("FileView.directoryIcon");
                classIcon = UIManager.getIcon("FileView.fileIcon");
                interfaceIcon = UIManager.getIcon("FileView.fileIcon");
                enumIcon = UIManager.getIcon("FileView.fileIcon");
                jarIcon = UIManager.getIcon("FileView.fileIcon");
                xmlIcon = UIManager.getIcon("FileView.fileIcon");
                fileIcon = UIManager.getIcon("FileView.fileIcon");
            }
        } catch (Exception e) {
            // 使用系统默认图标
            packageIcon = UIManager.getIcon("FileView.directoryIcon");
            classIcon = UIManager.getIcon("FileView.fileIcon");
            interfaceIcon = UIManager.getIcon("FileView.fileIcon");
            enumIcon = UIManager.getIcon("FileView.fileIcon");
            jarIcon = UIManager.getIcon("FileView.fileIcon");
            xmlIcon = UIManager.getIcon("FileView.fileIcon");
            fileIcon = UIManager.getIcon("FileView.fileIcon");
        }
    }
    
    /**
     * 自定义树节点渲染器，用于显示不同类型的图标
     */
    private class JavaElementTreeCellRenderer extends DefaultTreeCellRenderer {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                                                      boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            Object userObject = node.getUserObject();
            
            if (userObject instanceof JavaElementInfo) {
                JavaElementInfo elementInfo = (JavaElementInfo) userObject;
                String type = elementInfo.getType();
                
                // 设置显示文本为简单名称而不是全路径
                setText(elementInfo.getName());
                
                // 根据元素类型设置图标
                switch (type) {
                    case "JAR":
                        setIcon(jarIcon);
                        break;
                    case "PACKAGE":
                        setIcon(packageIcon);
                        break;
                    case "CLASS":
                        setIcon(classIcon);
                        break;
                    case "INTERFACE":
                        setIcon(interfaceIcon);
                        break;
                    case "ENUM":
                        setIcon(enumIcon);
                        break;
                    case "XML":
                    case "POM":
                        setIcon(xmlIcon);
                        break;
                    case "PROPERTIES":
                    case "MANIFEST":
                    case "OTHER_FILE":
                        setIcon(fileIcon);
                        break;
                    default:
                        setIcon(fileIcon); // 默认使用文件图标
                        break;
                }
            }
            
            return this;
        }
    }
    
    /**
     * 更新文件树显示
     * @param classNames 反编译后的类名列表
     */
    private void updateFileTree(java.util.Set<String> classNames) {
        // 清空现有树
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(currentJarFile.getName());
        root.setUserObject(new JavaElementInfo(currentJarFile.getName(), "JAR"));
        DefaultTreeModel treeModel = new DefaultTreeModel(root);
        fileTree.setModel(treeModel);
        
        // 按包名组织类
        java.util.Map<String, java.util.List<JavaElementInfo>> packageMap = new java.util.HashMap<>();
        
        // 添加Java类文件
        for (String className : classNames) {
            int lastDot = className.lastIndexOf('.');
            String packageName = (lastDot > 0) ? className.substring(0, lastDot) : "(default)";
            String simpleClassName = (lastDot > 0) ? className.substring(lastDot + 1) : className;
            
            // 获取元素类型
            JavaElementType elementType = decompiler.getElementType(className);
            JavaElementInfo elementInfo = new JavaElementInfo(simpleClassName, elementType.name(), className);
            
            packageMap.computeIfAbsent(packageName, k -> new java.util.ArrayList<>()).add(elementInfo);
        }
        
        // 添加非Java文件
        java.util.Set<String> nonJavaFiles = decompiler.getNonJavaFiles();
        for (String filePath : nonJavaFiles) {
            // 确定文件类型
            JavaElementType fileType = JavaElementType.OTHER_FILE;
            if (filePath.endsWith(".xml")) {
                if (filePath.endsWith("pom.xml") || filePath.contains("/META-INF/maven/") && filePath.endsWith(".xml")) {
                    fileType = JavaElementType.POM;
                } else {
                    fileType = JavaElementType.XML;
                }
            } else if (filePath.endsWith(".properties")) {
                fileType = JavaElementType.PROPERTIES;
            } else if (filePath.endsWith(".MF") || filePath.contains("META-INF/MANIFEST.MF")) {
                fileType = JavaElementType.MANIFEST;
            }
            
            // 获取文件名和路径
            String fileName = filePath;
            String directory = "";
            
            int lastSlash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
            if (lastSlash > 0) {
                fileName = filePath.substring(lastSlash + 1);
                directory = filePath.substring(0, lastSlash);
            }
            
            // 创建文件信息对象
            JavaElementInfo fileInfo = new JavaElementInfo(fileName, fileType.name(), filePath);
            
            // 将文件添加到相应的目录
            packageMap.computeIfAbsent(directory, k -> new java.util.ArrayList<>()).add(fileInfo);
        }
        
        // 按字母顺序排序包名
        java.util.List<String> sortedPackages = new java.util.ArrayList<>(packageMap.keySet());
        java.util.Collections.sort(sortedPackages);
        
        // 添加包和类到树
        for (String packageName : sortedPackages) {
            // 获取简单包名（只显示最后一级）
            String displayName = packageName;
            if (packageName.contains(".")) {
                String[] parts = packageName.split("\\.");
                // 创建层级结构
                DefaultMutableTreeNode currentNode = root;
                StringBuilder currentPath = new StringBuilder();
                
                for (int i = 0; i < parts.length; i++) {
                    if (i > 0) currentPath.append(".");
                    currentPath.append(parts[i]);
                    String currentPackage = currentPath.toString();
                    
                    // 检查当前路径是否已存在节点
                    boolean found = false;
                    for (int j = 0; j < currentNode.getChildCount(); j++) {
                        DefaultMutableTreeNode child = (DefaultMutableTreeNode) currentNode.getChildAt(j);
                        if (child.getUserObject() instanceof JavaElementInfo) {
                            JavaElementInfo info = (JavaElementInfo) child.getUserObject();
                            if ("PACKAGE".equals(info.getType()) && info.getFullName().equals(currentPackage)) {
                                currentNode = child;
                                found = true;
                                break;
                            }
                        }
                    }
                    
                    // 如果不存在，创建新节点
                    if (!found) {
                        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
                            new JavaElementInfo(parts[i], "PACKAGE", currentPackage));
                        currentNode.add(newNode);
                        currentNode = newNode;
                    }
                }
                
                // 将类添加到最后一级包节点
                java.util.List<JavaElementInfo> classesInPackage = packageMap.get(packageName);
                // 按字母顺序排序类名
                classesInPackage.sort(java.util.Comparator.comparing(JavaElementInfo::getName));
                
                for (JavaElementInfo elementInfo : classesInPackage) {
                    currentNode.add(new DefaultMutableTreeNode(elementInfo));
                }
            } else {
                // 处理默认包或单级包名
                DefaultMutableTreeNode packageNode = new DefaultMutableTreeNode(
                    new JavaElementInfo(displayName, "PACKAGE", packageName));
                root.add(packageNode);
                
                java.util.List<JavaElementInfo> classesInPackage = packageMap.get(packageName);
                // 按字母顺序排序类名
                classesInPackage.sort(java.util.Comparator.comparing(JavaElementInfo::getName));
                
                for (JavaElementInfo elementInfo : classesInPackage) {
                    packageNode.add(new DefaultMutableTreeNode(elementInfo));
                }
            }
            
            // 我们已经在上面处理了类的添加，不需要再执行下面的代码
        }
        
        // 展开根节点和第一级子节点
        fileTree.expandRow(0);
        for (int i = 0; i < root.getChildCount(); i++) {
            fileTree.expandPath(fileTree.getPathForRow(i + 1));
        }
    }
    
    /**
     * 添加日志信息
     * @param message 日志消息
     */
    private void log(String message) {
        SwingUtilities.invokeLater(() -> {
            logArea.append(message + "\n");
            // 滚动到最新日志
            logArea.setCaretPosition(logArea.getDocument().getLength());
        });
    }
    
    /**
     * 切换日志面板的显示状态
     */
    private void toggleLogPanel() {
        // 递归查找日志面板
        Component logPanel = findComponentByName(frame, "logPanel");
        
        if (logPanel != null) {
            boolean isVisible = logPanel.isVisible();
            logPanel.setVisible(!isVisible);
            
            // 重新验证和重绘内容面板
            frame.getContentPane().revalidate();
            frame.getContentPane().repaint();
            
            // 记录日志
            log(isVisible ? "日志面板已隐藏" : "日志面板已显示");
        }
    }
    
    /**
     * 递归查找指定名称的组件
     * @param container 容器
     * @param name 组件名称
     * @return 找到的组件，如果未找到则返回null
     */
    private Component findComponentByName(Container container, String name) {
        if (name.equals(container.getName())) {
            return container;
        }
        
        for (Component component : container.getComponents()) {
            if (name.equals(component.getName())) {
                return component;
            }
            
            if (component instanceof Container) {
                Component found = findComponentByName((Container) component, name);
                if (found != null) {
                    return found;
                }
            }
        }
        
        return null;
    }
    
    /**
     * 设置内存管理
     * 添加内存监控和垃圾回收建议
     */
    /**
     * 设置内存管理和监控
     * 定期检查内存使用情况，在内存使用过高时进行垃圾回收
     * 并在状态栏显示当前内存使用情况
     */
    private void setupMemoryManagement() {
        // 创建状态栏显示内存使用情况
        RoundedPanel statusPanel = new RoundedPanel(new BorderLayout(), new Color(240, 240, 240), 10, false);
        statusPanel.setBorder(BorderFactory.createEmptyBorder(5, 8, 5, 8));
        
        JLabel memoryLabel = new JLabel("内存使用: 0MB / 0MB");
        memoryLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11));
        statusPanel.add(memoryLabel, BorderLayout.EAST);
        
        // 添加状态栏到主窗口底部
        frame.add(statusPanel, BorderLayout.SOUTH);
        
        // 创建内存监控定时器，每2秒更新一次
        Timer memoryMonitor = new Timer(2000, e -> {
            // 获取当前内存使用情况
            Runtime runtime = Runtime.getRuntime();
            long totalMemory = runtime.totalMemory() / (1024 * 1024);
            long freeMemory = runtime.freeMemory() / (1024 * 1024);
            long usedMemory = totalMemory - freeMemory;
            long maxMemory = runtime.maxMemory() / (1024 * 1024);
            
            // 更新状态栏显示
            double usedPercentage = (double)usedMemory / maxMemory * 100;
            memoryLabel.setText(String.format("内存使用: %dMB / %dMB (%.1f%%)", 
                    usedMemory, maxMemory, usedPercentage));
            
            // 根据内存使用比例设置文本颜色
            if (usedPercentage > 80) {
                memoryLabel.setForeground(Color.RED);
            } else if (usedPercentage > 60) {
                memoryLabel.setForeground(new Color(255, 150, 0)); // 橙色
            } else {
                memoryLabel.setForeground(Color.BLACK);
            }
            
            // 如果内存使用超过最大内存的75%，建议进行垃圾回收
            if (usedPercentage > 75) {
                System.gc(); // 建议JVM进行垃圾回收
                log("内存使用较高，已请求垃圾回收。当前使用: " + usedMemory + "MB / 最大: " + maxMemory + "MB");
            }
        });
        
        // 启动内存监控
        memoryMonitor.start();
        
        // 添加手动垃圾回收按钮和日志按钮到状态栏
        ModernButton gcButton = new ModernButton("GC", new Color(120, 120, 120));
        gcButton.setToolTipText("手动请求垃圾回收");
        gcButton.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 10));
        gcButton.addActionListener(e -> {
            System.gc();
            log("已手动请求垃圾回收");
        });
        
        ModernButton logButton = new ModernButton("日志", new Color(70, 130, 180));
        logButton.setToolTipText("显示/隐藏日志面板");
        logButton.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 10));
        logButton.addActionListener(e -> {
            toggleLogPanel();
        });
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
        buttonPanel.add(gcButton);
        buttonPanel.add(logButton);
        statusPanel.add(buttonPanel, BorderLayout.WEST);
    }
}